package com.leo.erp.service.impl;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.leo.erp.dao.AccountHeadMapper;
import com.leo.erp.dao.DepotHeadMapper;
import com.leo.erp.dao.SupplierMapper;
import com.leo.erp.dto.SupplierExecution;
import com.leo.erp.entity.AccountHead;
import com.leo.erp.entity.DepotHead;
import com.leo.erp.entity.Supplier;
import com.leo.erp.entity.User;
import com.leo.erp.enums.SupplierStateEnum;
import com.leo.erp.service.LogService;
import com.leo.erp.service.SupplierService;
import com.leo.erp.util.GlobalRuntimeException;
import com.leo.erp.util.StringUtil;

@Service
public class SupplierServiceImpl implements SupplierService{
	@Autowired
	private SupplierMapper supplierMapper;
	@Autowired
	private LogService logService;
	@Autowired
	private AccountHeadMapper accountHeadMapper;
	@Autowired
	private DepotHeadMapper depotHeadMapper;


	@Override
	public SupplierExecution findUserCustomer() {
		SupplierExecution se = new SupplierExecution();
		QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("type", "客户");
		queryWrapper.ne("deleteFlag", "1");
		queryWrapper.orderByDesc("supplierId");
		try {
			List<Supplier> list = supplierMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				se.setState(SupplierStateEnum.SUCCESS.getState());
				se.setSupplierList(list);
			}else {
				se.setState(SupplierStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return se;
	}

	@Override
	public SupplierExecution checkIsNameExist(int id, String name) {
		SupplierExecution se = new SupplierExecution();
		QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
		queryWrapper.ne("supplierId", id);
		queryWrapper.eq("supplier", name);
		queryWrapper.ne("deleteFlag", "1");
		try {
			List<Supplier> list = supplierMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				se.setState(SupplierStateEnum.SUCCESS.getState());
			}else {
				se.setState(SupplierStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return se;
	}

	@Override
	@Transactional
	public SupplierExecution insertSupplier(String beanJson, HttpServletRequest request) throws GlobalRuntimeException {
		SupplierExecution se = new SupplierExecution();
		Supplier supplier = JSONObject.parseObject(beanJson, Supplier.class);
		//session
		User user = (User) request.getSession().getAttribute("user");
		supplier.setTenantId(user.getUserId());
		try {
			int effectedNum = supplierMapper.insert(supplier);
			if(effectedNum > 0) {
				logService.insertLog("商家", "新增" + supplier.getSupplier(), request);
				se.setState(SupplierStateEnum.SUCCESS.getState());
			}else {
				se.setState(SupplierStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return se;
	}

	@Override
	public SupplierExecution findBySelectSup() {
		SupplierExecution se =new SupplierExecution();
		QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
		queryWrapper.like("type", "供应商");
		queryWrapper.eq("enabled", 1);
		queryWrapper.ne("deleteFlag", "1");
		queryWrapper.orderByDesc("supplierId");
		try {
			List<Supplier> list = supplierMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				se.setState(SupplierStateEnum.SUCCESS.getState());
				se.setSupplierList(list);
			}else {
				se.setState(SupplierStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return se;
	}

	@Override
	public SupplierExecution findBySelectCus() {
		SupplierExecution se = new SupplierExecution();
		QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
		queryWrapper.like("type", "客户");
		queryWrapper.eq("enabled", 1);
		queryWrapper.ne("deleteFlag", "1");
		queryWrapper.orderByDesc("supplierId");
		
		try {
			List<Supplier> list = supplierMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				se.setState(SupplierStateEnum.SUCCESS.getState());
				se.setSupplierList(list);
			}else {
				se.setState(SupplierStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return se;
	}

	@Override
	public SupplierExecution findBySelectRetail() {
		SupplierExecution se = new SupplierExecution();
		QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
		queryWrapper.like("type", "会员");
		queryWrapper.eq("enabled", 1);
		queryWrapper.ne("deleteFlag", "1");
		queryWrapper.orderByDesc("supplierId");
		try {
			List<Supplier> list = supplierMapper.selectList(queryWrapper);
			if(list.size() > 0) {
				se.setState(SupplierStateEnum.SUCCESS.getState());
				se.setSupplierList(list);
			}else {
				se.setState(SupplierStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return se;
	}

	@Override
	public SupplierExecution updateSupplier(String beanJson, int supplierId, HttpServletRequest request) {
		SupplierExecution se = new SupplierExecution();
		Supplier supplier = JSONObject.parseObject(beanJson, Supplier.class);
		if(Double.toString(supplier.getBeginNeedPay()) == null) {
			supplier.setBeginNeedPay(0);
		}
		if(Double.toString(supplier.getBeginNeedGet()) == null) {
			supplier.setBeginNeedGet(0);
		}
		//session
		User user = (User) request.getSession().getAttribute("user");
		
		supplier.setSupplierId(supplierId);
		supplier.setTenantId(user.getUserId());
		try {
			int effectedNum = supplierMapper.updateById(supplier);
			if(effectedNum > 0) {
				logService.insertLog("商家", "修改" + supplier.getSupplier().toString(), request);
				se.setState(SupplierStateEnum.SUCCESS.getState());
			}else {
				se.setState(SupplierStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return se;
	}

	@Override
	public SupplierExecution getList(String supplier, String type, String phoneNum, String telephone,
			String description, int currentPage, int pageSize) {
		SupplierExecution se = new SupplierExecution();
		QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
		
		//判断
		if(supplier != null && supplier != "") {
			queryWrapper.like("supplier", supplier);
		}
		if(type != null && type != "") {
			queryWrapper.like("type", type);
		}
		if(phoneNum != null && phoneNum != "") {
			queryWrapper.like("phoneNum", phoneNum);
		}
		if(telephone != null && telephone != "") {
			queryWrapper.like("telephone", telephone);
		}
		if(description != null && description != "") {
			queryWrapper.like("description", description);
		}
		queryWrapper.ne("deleteFlag", "1");
		
		Page<Supplier> page = new Page<>(currentPage, pageSize);//分页查询
		IPage<Map<String, Object>> iPage = supplierMapper.selectMapsPage(page, queryWrapper);
		if(iPage.getRecords().size() > 0) {
			se.setState(SupplierStateEnum.SUCCESS.getState());
			se.setPages(page.getPages());//总页数
			se.setTotal(iPage.getTotal());//总记录数
			se.setSupplierPageList(iPage.getRecords());
		}else{
			se.setState(SupplierStateEnum.OFFLINE.getState());
		}
		
		return se;
	}

	/**
	 * 正常删除，要考虑数据完整性，进行完整性校验
	 */
	@Override
	@Transactional
	public SupplierExecution batchDeleteSupplierByIdsNormal(String ids) {
		SupplierExecution se = new SupplierExecution();
		/**
         * 校验
         * 1、财务主表	tb_account_head
         * 2、单据主表	tb_depot_head
         * 是否有相关数据
         * */
		if(StringUtil.isEmpty(ids)) {
			se.setState(SupplierStateEnum.OFFLINE.getState());
			return se;
		}
		
		List<Long> idList = StringUtil.strToLongList(ids);//转换成数组
		
		/**
		 * 检验财务主表tb_account_head
		 */
		try {
			QueryWrapper<AccountHead> queryAccountHead = new QueryWrapper<>();
			queryAccountHead.in("organId", idList);
			List<AccountHead> accountHeadList = accountHeadMapper.selectList(queryAccountHead);
			if(accountHeadList.size() > 0) {
				//有数据,可以执行强制删除
				se.setState(SupplierStateEnum.DELETE.getState());
				return se;
				//throw new GlobalRuntimeException("检测到存在依赖数据，是否强制删除？");
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		/**
		 * 检验单据主表tb_depot_head
		 */
		try {
			QueryWrapper<DepotHead> queryDepotHead = new QueryWrapper<>();
			queryDepotHead.in("organId", idList);
			List<DepotHead> depotHeadList = depotHeadMapper.selectList(queryDepotHead);
			if(depotHeadList.size() > 0) {
				se.setState(SupplierStateEnum.DELETE.getState());
				return se;
				//throw new GlobalRuntimeException("检测到存在依赖数据，是否强制删除？");
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		/**
		 * 校验通过执行删除操作
		 */
		int effectedNum = batchDeleteSupplierByIds(ids);
		if(effectedNum > 0) {
			se.setState(SupplierStateEnum.SUCCESS.getState());
		}else {
			se.setState(SupplierStateEnum.OFFLINE.getState());
		}
		
		return se;
	}
	
	@Transactional
	@Override
	public int batchDeleteSupplierByIds(String ids) {
		StringBuffer sb = new StringBuffer();
		List<Long> idList = StringUtil.strToLongList(ids);
		QueryWrapper<Supplier> querySupplier = new QueryWrapper<>();
		querySupplier.in("supplierId", idList);
		List<Supplier> list = supplierMapper.selectList(querySupplier);
		for(Supplier supplier : list) {
			sb.append("[").append(supplier.getSupplier()).append("]");
		}
		logService.insertLog("商家", "删除" + sb.toString(), ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
		HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		User user = (User) request.getSession().getAttribute("user");
		int effectedNum = 0;
		try {
			Supplier supplier = new Supplier();
			supplier.setDeleteFlag("1");
			supplier.setTenantId(user.getUserId());
			UpdateWrapper<Supplier> updateWrapper = new UpdateWrapper<>();
			updateWrapper.in("supplierId", idList);
			
			effectedNum = supplierMapper.update(supplier, updateWrapper);
			
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return effectedNum;
	}

	/**
	 * 批量启动
	 */
	@Override
	@Transactional
	public SupplierExecution batchSetEnable(int enabled, String supplierIDs) {
		SupplierExecution se = new SupplierExecution();
		List<Long> ids = StringUtil.strToLongList(supplierIDs);//转换成数组
		UpdateWrapper<Supplier> updateWrapper = new UpdateWrapper<>();
		Supplier supplier = new Supplier();
		//session
		HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
		User user = (User) request.getSession().getAttribute("user");
		
		supplier.setEnabled(enabled);
		supplier.setTenantId(user.getUserId());
		
		//条件
		updateWrapper.in("supplierId", ids);
		try {
			int effectedNum = supplierMapper.update(supplier, updateWrapper);
			if(effectedNum > 0) {
				logService.insertLog("商家", "修改:" + supplierIDs, ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
				se.setState(SupplierStateEnum.SUCCESS.getState());
			}else {
				se.setState(SupplierStateEnum.OFFLINE.getState());
			}
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return se;
	}

	@Override
	public List<Supplier> findByAll(String supplier, String type, String phoneNum, String telephone,
			String description) {
		List<Supplier> list = null;
		//查询条件
		QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
		//判断
		if(supplier != null && supplier != "") {
			queryWrapper.like("supplier", supplier);
		}
		if(type != null && type != "") {
			queryWrapper.like("type", type);
		}
		if(phoneNum != null && phoneNum != "") {
			queryWrapper.like("phoneNum", phoneNum);
		}
		if(telephone != null && telephone != "") {
			queryWrapper.like("telephone", telephone);
		}
		if(description != null && description != "") {
			queryWrapper.like("description", description);
		}
		queryWrapper.ne("deleteFlag", "1");
		
		try {
			list = supplierMapper.selectList(queryWrapper);
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
		}
		
		return list;
	}

	@Override
	@Transactional
	public SupplierExecution importExcel(List<Supplier> mList) {
		SupplierExecution se = new SupplierExecution();
		try {
			for(Supplier s : mList) {
				supplierMapper.insert(s);
			}
			se.setState(SupplierStateEnum.SUCCESS.getState());
		} catch (GlobalRuntimeException e) {
			e.printStackTrace();
			se.setState(SupplierStateEnum.OFFLINE.getState());
		}
		
		return se;
	}
	
	
	
	
	
	
	
	
	
	
	
	
}
